import type { RouteLocationNormalized, RouteRecordRaw } from 'vue-router'
import { useUserStore, useAuthMenuAndButtonStore } from '@/stores'
import { storeToRefs } from 'pinia'
import router from '@/router'
export default function usePermission() {
  const userStore = useUserStore()
  return {
    accessRouter(route: RouteLocationNormalized | RouteRecordRaw) {
      return (
        !route.meta?.requiresAuth ||
        !route.meta?.roles ||
        route.meta?.roles?.includes('*') ||
        route.meta?.roles?.includes(userStore.userInfo.role)
      )
    },
    findFirstPermissionRoute(_routers: any, role: string) {
      const cloneRouters = [..._routers]
      while (cloneRouters.length) {
        const firstElement = cloneRouters.shift()
        if (
          firstElement?.meta?.roles?.find((el: string[]) => {
            return el.includes('*') || el.includes(role)
          })
        )
          return { name: firstElement.name }
        if (firstElement?.children) {
          cloneRouters.push(...firstElement.children)
        }
      }
      return null
    },
    hasCurrentButton(currentButtonCode: string) {
      const { authButtonList } = storeToRefs(useAuthMenuAndButtonStore())

      const currentPage = router.currentRoute.value.name as string
      if (!currentPage) return false
      const currentPageAuthButtonList = authButtonList.value[currentPage]

      if (currentPageAuthButtonList.includes(currentButtonCode)) {
        return true
      } else {
        return false
      }
    }
    // You can add any rules you want
  }
}
